package com.donfu.common.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
/**
     * 视频工具类
     *
     * @Author: szw
     * @Date: 2020/7/9 9:42
     */
    public class VideoUtil {
        private static final Logger LOGGER = LoggerFactory.getLogger(VideoUtil.class);

        /**
         * 通过Javacv的方式获取视频截图
         *
         * @param filePath 视频文件路径
         * @return Map<String, Object>
         */
        public static Map<String, Object> getScreenshot(String filePath) {
            try {
                LOGGER.debug("截取视频截图开始：" + System.currentTimeMillis());
                Map<String, Object> result = new HashMap<String, Object>();
                FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(filePath);

                // 第一帧图片存储位置
                String targerFilePath = filePath.substring(0, filePath.lastIndexOf("\\"));
                // 视频文件名
                String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
                // 图片名称
                String targetFileName = fileName.substring(0, fileName.lastIndexOf("."));
                LOGGER.debug("图片名称是：" + targetFileName);

                grabber.start();
                //设置视频截取帧（默认取第一帧）
                Frame frame = grabber.grabImage();
                Java2DFrameConverter converter = new Java2DFrameConverter();
                //绘制图片
                BufferedImage bi = converter.getBufferedImage(frame);
                //图片的类型
                String imageMat = "jpg";
                //图片的完整路径
                String imagePath = targerFilePath + File.separator + targetFileName + "." + imageMat;
                //创建文件
                File output = new File(imagePath);
                ImageIO.write(bi, imageMat, output);
                grabber.stop();
                LOGGER.debug("截取视频截图结束：" + System.currentTimeMillis());
                return result;
            } catch (Exception e) {
                return null;
            }
        }

    }
